package com.sambo.inspection.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonElement;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.model.HttpParams;
import com.sambo.inspection.R;
import com.sambo.inspection.activity.support.BaseActivity;
import com.sambo.inspection.adapter.MediaListAdapter;
import com.sambo.inspection.bean.GlobleBean;
import com.sambo.inspection.bean.MediaFileBean;
import com.sambo.inspection.bean.OrderFileBean;
import com.sambo.inspection.bean.UploadFileResponseBean;
import com.sambo.inspection.bean.WorkReportBean;
import com.sambo.inspection.adapter.FullyGridLayoutManager;
import com.sambo.inspection.adapter.GridImageAdapter;
import com.sambo.inspection.component.ZnkConfirmDialog;
import com.sambo.inspection.component.ZnkProgressDialog;
import com.sambo.inspection.http.HttpClient;
import com.sambo.inspection.http.HttpResponseHandler;
import com.sambo.inspection.http.Urls;
import com.sambo.inspection.util.JsonUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class EventReportDetailActivity extends BaseActivity implements View.OnClickListener {

    ImageView ivBack;
    RecyclerView rvUploadRes;
    TextView tvCommit;
    EditText etCheckNumber;
    EditText etTitle;
    EditText etContent;

    private GridImageAdapter mediaPickerAdapter;
    private List<MediaFileBean> selectList = new ArrayList<>();

    private List<UploadFileResponseBean> uploadFileList = new ArrayList<>();
    private List<OrderFileBean> orderFileBeanList = new ArrayList<>();

    private List<String> delList = new ArrayList<>();
    private List<String> uploadList = new ArrayList<>();

    private int uploadCount;
    private int delCount;

    private boolean uploadFlag;
    private boolean delFlag;

    private WorkReportBean mWorkReportBean;

    private ZnkProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_report_detail);

        ivBack = findViewById(R.id.iv_back);
        rvUploadRes = findViewById(R.id.rv_upload_res);
        tvCommit = findViewById(R.id.tv_commit);
        etCheckNumber = findViewById(R.id.et_check_number);
        etTitle = findViewById(R.id.et_title);
        etContent = findViewById(R.id.et_content);

        ivBack.setOnClickListener(this);
        tvCommit.setOnClickListener(this);

        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        rvUploadRes.setLayoutManager(manager);

        mWorkReportBean = (WorkReportBean) getIntent().getSerializableExtra("model");

//        mWorkReportBean = new WorkReportBean();
//        mWorkReportBean.setState("2");

        if (mWorkReportBean != null) {
            etCheckNumber.setText(mWorkReportBean.getCheckPointCode());
            etTitle.setText(mWorkReportBean.getTitle());
            etContent.setText(mWorkReportBean.getContent());

            getMediaFileInfo();
        }

        initMediaPickerAdapter();

//        MediaFileBean bean = new MediaFileBean();
//        bean.setMediaType(2);
//        bean.setType(2);
//        bean.setUrl("http://9890.vod.myqcloud.com/9890_4e292f9a3dd011e6b4078980237cc3d3.f20.mp4");
//        selectList.add(bean);
//
//        bean = new MediaFileBean();
//        bean.setMediaType(1);
//        bean.setType(2);
//        bean.setUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1550724943361&di=6f89d5f6dc0c95d8dbc362b0c59e274a&imgtype=0&src=http%3A%2F%2Fimg67.hbzhan.com%2F9%2F20151019%2F635808657133009174192.jpg");
//        selectList.add(bean);

    }

    private void initMediaPickerAdapter() {
        mediaPickerAdapter = new GridImageAdapter(this, onAddPicClickListener);
        mediaPickerAdapter.setList(selectList);
        mediaPickerAdapter.setSelectMax(4);
        rvUploadRes.setAdapter(mediaPickerAdapter);

        mediaPickerAdapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    MediaFileBean media = selectList.get(position);

                    if (media.getType() == 1) {
                        String pictureType = media.getLocalMedia().getPictureType();
                        int mediaType = PictureMimeType.pictureToVideo(pictureType);
                        switch (mediaType) {
                            case 1:
                                // 预览图片 可自定长按保存路径
                                List<LocalMedia> paramList = new ArrayList<>();
                                paramList.add(media.getLocalMedia());
                                PictureSelector.create(EventReportDetailActivity.this).themeStyle(R.style.picture_default_style).openExternalPreview(0, paramList);
                                break;
                            case 2:
                                // 预览视频
                                PictureSelector.create(EventReportDetailActivity.this).externalPictureVideo(media.getLocalMedia().getPath());
                                break;
                        }

                    } else if (media.getType() == 2) {
                        switch (media.getMediaType()) {
                            case 1:
                                Intent imageIntent = new Intent(EventReportDetailActivity.this, ImageShowActivity.class);
                                imageIntent.putExtra("imageUrl", media.getUrl());
                                startActivity(imageIntent);
                                overridePendingTransition(com.luck.picture.lib.R.anim.a5, 0);
                                break;
                            case 2:
                                Intent videoIntent = new Intent(EventReportDetailActivity.this, VideoPlayActivity.class);
                                videoIntent.putExtra("mediaUrl", media.getUrl());
                                startActivity(videoIntent);
                                break;
                        }
                    }

                }
            }
        });
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            // 进入相册 以下是例子：不需要的api可以不写
            PictureSelector.create(EventReportDetailActivity.this)
                    .openGallery(PictureMimeType.ofAll())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                    .maxSelectNum(4)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .imageSpanCount(4)// 每行显示个数
                    .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                    .previewImage(true)// 是否可预览图片
                    .previewVideo(true)// 是否可预览视频
                    .enablePreviewAudio(false) // 是否可播放音频
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                    .enableCrop(false)// 是否裁剪
                    .compress(true)// 是否压缩
                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                    .compressSavePath(getPath())//压缩图片保存地址
                    //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                    .withAspectRatio(aspect_ratio_x, aspect_ratio_y)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                    .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                    .isGif(false)// 是否显示gif图片
                    .freeStyleCropEnabled(false)// 裁剪框是否可拖拽
                    .circleDimmedLayer(false)// 是否圆形裁剪
                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                    .openClickSound(false)// 是否开启点击声音
//                    .selectionMedia(selectList)// 是否传入已选图片
                    //.isDragFrame(false)// 是否可拖动裁剪框(固定)
                    .videoMaxSecond(60)
//                    .videoMinSecond(10)
                    //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                    //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                    //.rotateEnabled(true) // 裁剪是否可旋转图片
                    //.scaleEnabled(true)// 裁剪是否可放大缩小图片
                    //.videoQuality()// 视频录制质量 0 or 1
//                    .videoSecond()//显示多少秒以内的视频or音频也可适用
                    .recordVideoSecond(60)//录制视频秒数 默认60s
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code

        }

    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> localMediaList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    MediaFileBean bean;

                    for (LocalMedia media : localMediaList) {
                        bean = new MediaFileBean();
                        bean.setType(1);
                        bean.setLocalMedia(media);
                        selectList.add(bean);
                    }
                    mediaPickerAdapter.setList(selectList);
                    mediaPickerAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_commit:
                if (checkInput()) {
                    ZnkConfirmDialog dialog = ZnkConfirmDialog.createDialog(this, "确认要提交事件吗？",
                            new ZnkConfirmDialog.OnClickCallBack() {
                                @Override
                                public void exec() {
                                    updateOrderInfo();
                                }
                            }, null);

                    dialog.show();
                }
                break;
        }
    }

    private boolean checkInput() {
        if (TextUtils.isEmpty(etTitle.getText().toString())) {
            Toast.makeText(this, "必须输入标题", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (TextUtils.isEmpty(etContent.getText().toString())) {
            Toast.makeText(this, "必须输入事件内容", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    private void updateOrderInfo() {
        uploadFileList.clear();
        uploadList.clear();
        delList.clear();
        uploadFlag = false;
        delFlag = false;
        uploadCount = 0;
        delCount = 0;

        dialog = ZnkProgressDialog.createLoadingDialog(this, "保存中");
        dialog.show();

        uploadMediaFile();
        deleteMediaFile();
    }

    private void getMediaFileInfo() {

        if (mWorkReportBean == null) {
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put("orderid", String.valueOf(mWorkReportBean.getId()));

        HttpClient.get(this, Urls.API_SERVER_HOST + Urls.GET_ORDER_FILES, params,
                new HttpResponseHandler() {
                    @Override
                    public void onInnovationSuccess(JsonElement value) {
                        super.onInnovationSuccess(value);
                        OrderFileBean[] response = JsonUtil.toObj(value.toString(), OrderFileBean[].class);

                        selectList.clear();
                        orderFileBeanList.clear();

                        if (response != null && response.length > 0) {

                            orderFileBeanList.addAll(Arrays.asList(response));

                            MediaFileBean bean;

                            for (OrderFileBean orderFileBean : response) {
                                bean = new MediaFileBean();
                                bean.setId(orderFileBean.getId());
                                bean.setUrl(orderFileBean.getUrl());
                                bean.setType(2);
                                bean.setBusinessType(orderFileBean.getBusinessType());
                                if (TextUtils.equals("0", orderFileBean.getFileType())) {
                                    bean.setMediaType(1);
                                } else {
                                    bean.setMediaType(2);
                                }
                                selectList.add(bean);
                            }
                        }

                        mediaPickerAdapter.notifyDataSetChanged();
                    }

                }, new HttpClient.NetworkUnavailableListener() {
                    @Override
                    public void networkUnavailable() {
                        Toast.makeText(EventReportDetailActivity.this, "", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void uploadMediaFile() {

        if (selectList.size() == 0) {
            uploadFlag = true;
            checkResult();
            return;
        }

        List<String> mediaPathList = new ArrayList<>();

        for (MediaFileBean bean : selectList) {
            if (bean.getLocalMedia() != null) {
                mediaPathList.add(bean.getLocalMedia().getPath());
            }
        }

        if (mediaPathList.size() == 0) {
            uploadFlag = true;
            checkResult();
            return;
        }

        uploadList = mediaPathList;
        uploadCount = 0;

        upload();
    }

    private void upload() {

        if (uploadCount == uploadList.size()) {
            uploadFlag = true;
            checkResult();
            return;
        }

        HttpParams params = new HttpParams();
        params.put("file", new File(uploadList.get(uploadCount++)));

        HttpClient.upload(this, Urls.API_SERVER_HOST + Urls.IMG_UPLOAD, params,
                new HttpResponseHandler() {
                    @Override
                    public void onInnovationSuccess(JsonElement value) {
                        super.onInnovationSuccess(value);
                        UploadFileResponseBean bean = JsonUtil.toObj(value.toString(), UploadFileResponseBean.class);

                        if (bean != null) {
                            uploadFileList.add(bean);
                            upload();
                        }
                    }

                    @Override
                    public void onInnovationFailure(String msg) {
                        super.onInnovationFailure(msg);
                        Toast.makeText(EventReportDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                }, null);
    }

    private void checkResult() {
        if (uploadFlag && delFlag) {
            saveWorkOrder();
        }
    }

    private void saveWorkOrder() {

        if (mWorkReportBean == null) {

            WorkReportBean requestBean = new WorkReportBean();
            requestBean.setContent(etContent.getText().toString());
            requestBean.setCreatedBy(GlobleBean.getInstance().getUserName());
            requestBean.setTitle(etTitle.getText().toString());
            requestBean.setDeptId(GlobleBean.getInstance().getDeptID());
            requestBean.setType("1");
            requestBean.setState("1");

            requestBean.setDirList(convertDirString(uploadFileList));

            HttpClient.post(this, Urls.API_SERVER_HOST + Urls.SAVE_ORDER, requestBean,
                    new HttpResponseHandler() {
                        @Override
                        public void onInnovationSuccess(JsonElement value) {
                            super.onInnovationSuccess(value);
                            Toast.makeText(EventReportDetailActivity.this, "事件上报成功", Toast.LENGTH_SHORT).show();
                            finish();
                        }

                        @Override
                        public void onInnovationFailure(String msg) {
                            super.onInnovationFailure(msg);
                            Toast.makeText(EventReportDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    }, null);
        } else {

            mWorkReportBean.setContent(etContent.getText().toString());
            mWorkReportBean.setTitle(etTitle.getText().toString());
            mWorkReportBean.setDirList(convertDirString(uploadFileList));

            HttpClient.post(this, Urls.API_SERVER_HOST + Urls.EDIT_ORDER, mWorkReportBean,
                    new HttpResponseHandler() {
                        @Override
                        public void onInnovationSuccess(JsonElement value) {
                            super.onInnovationSuccess(value);
                            Toast.makeText(EventReportDetailActivity.this, "事件更新成功", Toast.LENGTH_SHORT).show();
                            finish();
                        }

                        @Override
                        public void onInnovationFailure(String msg) {
                            super.onInnovationFailure(msg);
                            Toast.makeText(EventReportDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    }, null);

            dialog.dismiss();
        }

    }

    private void deleteMediaFile() {

        List<String> mediaIDList = new ArrayList<>();

        Map<String, MediaFileBean> dataMap = new HashMap<>();

        for (MediaFileBean bean : selectList) {
            if (bean.getId() != 0) {
                dataMap.put(String.valueOf(bean.getId()), bean);
            }
        }

        for (OrderFileBean bean : orderFileBeanList) {
            if (!dataMap.containsKey(String.valueOf(bean.getId()))) {
                mediaIDList.add(String.valueOf(bean.getId()));
            }
        }

        if (mediaIDList.size() == 0) {
            delFlag = true;
            checkResult();
            return;
        }

        delList = mediaIDList;
        delCount = 0;

        delMediaFile();
    }

    private void delMediaFile() {

        if (delCount == delList.size()) {
            delFlag = true;
            checkResult();
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put("deleteId", delList.get(delCount++));

        HttpClient.get(this, Urls.API_SERVER_HOST + Urls.DEL_ORDER_FILE, params,
                new HttpResponseHandler() {
                    @Override
                    public void onInnovationSuccess(JsonElement value) {
                        super.onInnovationSuccess(value);
                        delMediaFile();
                    }

                    @Override
                    public void onInnovationFailure(String msg) {
                        super.onInnovationFailure(msg);
                        Toast.makeText(EventReportDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                }, null);
    }

    /**
     * 自定义压缩存储地址
     *
     * @return
     */
    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/com.sambo.inspection/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }

    private String convertDirString(List<UploadFileResponseBean> dataList) {
        if (dataList == null || dataList.size() == 0) {
            return null;
        }

        StringBuilder builder = new StringBuilder();

        for (UploadFileResponseBean bean : dataList) {
            builder.append(bean.getDir());
            builder.append(";");
            builder.append(bean.getSize());
            builder.append(";");
            builder.append(bean.getName());
            builder.append(";");
            builder.append(bean.getSrc());
            builder.append(",");
        }

        return builder.deleteCharAt(builder.length() - 1).toString();
    }
}
